<template>
    <div class="img-up">
        <div class="img-box">
            <div class="img-item" v-for="(item, index) in fileArr" :key="index">
                <el-image
                    style="width: 100%; height: 100%"
                    fit="contain"
                    :src="previewUrl + item + '?maxHeight=85&isOriginal=false&isSameRatio=true&isOrientation=false'"
                    :preview-src-list="[previewUrl + item]"
                >
                    <div slot="placeholder" style="width: 100%; height: 100%" class="center">
                        <i class="el-icon-loading f16"></i>
                    </div>
                    <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline"></i>
                    </div>
                </el-image>
                <i v-if="!disabled" class="el-icon-delete delete-icon" @click.stop="del(index)"></i>
            </div>
            <div class="img-item" @click.capture="inputPreClick" v-if="!disabled">
                <input
                    v-if="showInput"
                    ref="inputImg"
                    type="file"
                    accept="image/*"
                    capture="camera"
                    @change.capture="uploadMulFile"
                />
                <i class="el-icon-camera f32" />
            </div>
        </div>
    </div>
</template>
<!--audio/* 表示音频文件 HTML5-->
<!--video/* 表示视频文件 HTML5-->
<!--image/* 表示图片文件 HTML5-->
<script>
import axios from 'axios'
import url from '@/common/url-config'
import { getFileToken } from '@/common/api/common'
const { fileBaseUrl, imgPreviewUrl } = url
let me

export default {
    name: 'ImgUp',
    data() {
        return {
            previewUrl: fileBaseUrl + imgPreviewUrl,
            fileArr: [],
            uploadFile: [],
            type: 'imgUp',
            loading: null,
            showInput: true, //用于解决change事件触发一次之后，再次选择图片，偶尔不触发的情况
        }
    },
    computed: {
        disabled() {
            return this.$attrs.disabled
        },
    },
    mounted() {
        me = this
        let val = this.$vnode.data.props.value
        if (val) {
            this.fileArr = JSON.parse(val)
        }
    },
    destroyed() {
        this.loading = null
    },
    methods: {
        del(index) {
            this.fileArr.splice(index, 1)
        },
        async readyUpload() {
            let fileToken = this.fileToken
            let uploadFile = this.uploadFile
            let fileIndex = 0
            const reader = new FileReader()
            reader.readAsBinaryString(uploadFile[fileIndex]) //读法异步的
            reader.onloadend = async () => {
                // 这个事件在读取结束后，无论成功或者失败都会触发
                if (reader.error) {
                    // console.log(reader.error)
                    this.$message.error(`读取文件错误，原因：${reader.error}`)
                } else {
                    if (fileIndex < uploadFile.length) {
                        reader.readAsBinaryString(uploadFile[fileIndex]) //读法异步的
                        me.uploadFileServer(fileToken, uploadFile[fileIndex], fileIndex)
                        fileIndex++
                    } else {
                        setTimeout(() => {
                            me.showInput = true
                        })
                    }
                }
            }
        },
        uploadFileServer(token, file, fileIndex) {
            const uploadFile = new FormData()
            uploadFile.append('file', file)
            axios({
                method: 'post',
                url: '/file/api/Upload/v1/Single',
                headers: { 'Content-Type': 'multipart/form-data', token },
                data: uploadFile,
            })
                .then(res => {
                    if (res.data.code == 200) {
                        this.fileArr.push(res.data.data.id)
                    }
                })
                .catch(e => {
                    console.log(e)
                })
                .finally(() => {
                    if (fileIndex + 1 === this.uploadFile.length) {
                        this.$emit('input', JSON.stringify(this.fileArr))
                    }
                    this.loading.close()
                })
        },
        inputPreClick(e) {
            if (this.fileArr.length >= this.$attrs.imgNumber) {
                e.stopPropagation()
                e.preventDefault()
                return this.$message({
                    type: 'error',
                    message: '图片允许最大数量为' + this.$attrs.imgNumber,
                    duration: 2 * 1000,
                })
            }
        },
        async uploadMulFile(e) {
            this.showInput = false
            const me = this
            const uploadFile = e.target.files
            if (this.fileArr.length + uploadFile.length > this.$attrs.imgNumber) {
                setTimeout(() => {
                    me.showInput = true
                })
                return this.$message({
                    type: 'error',
                    message: '图片允许最大数量为' + this.$attrs.imgNumber,
                    duration: 2 * 1000,
                })
            }

            this.uploadFile = uploadFile
            this.loading = this.$loading({
                lock: true,
                text: '正在上传图片...',
            })
            try {
                let res = await getFileToken()
                this.fileToken = res?.data?.token
                this.readyUpload()
            } catch (e) {
                console.log(e)
                this.loading.close()
            }
        },
    },
}
</script>

<style lang="scss" scoped>
.img-up {
    width: 100%;
    position: relative;
    font-size: 60px;
    input {
        position: absolute;
        opacity: 0;
        width: 75px;
        height: 75px;
    }
    .img-box {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
        .img-item {
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 10px;
            margin-bottom: 10px;
            width: 75px;
            height: 75px;
            opacity: 1;
            background: #ffffff;
            border: 2px dashed #d3e5ff;
            border-radius: 11px;
            > img {
                max-width: 100%;
                height: 100%;
            }
            .delete-icon {
                color: #666;
                font-size: 16px;
                position: absolute;
                top: -8px;
                right: -8px;
            }
        }
    }
}
</style>
